package com.dongnao.network.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

/**
 * 群聊客户端
 */
public class GroupChatClient {

    Selector selector;
    static final int port = 8899;
    String userName;
    SocketChannel socketChannel;

    public GroupChatClient() throws IOException {
        selector = Selector.open();
        socketChannel = SocketChannel.open(new InetSocketAddress("localhost", port));
        socketChannel.configureBlocking(false);
        socketChannel.register(selector, SelectionKey.OP_READ);
        userName = socketChannel.getLocalAddress().toString().substring(1);
        System.out.println(userName + " 准备就绪");
    }

    void sendMessageToServer(String message) throws IOException {
        message = userName + "说：" + message;
        socketChannel.write(ByteBuffer.wrap(message.getBytes()));
    }

    void readMessageFromServer() throws IOException {
        int num = selector.select();
//        System.out.println("读数据num=" + num);
        if (num > 0) {
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                iterator.remove();

                if (key.isReadable()) {
                    SocketChannel channel = (SocketChannel) key.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    channel.read(buffer);
                    System.out.println("接收到消息[ " + new String(buffer.array()) + " ]");
                }
            }
        } else {
            System.out.println("暂无可用通道");
        }
    }

    public static void main(String[] args) throws IOException {
        GroupChatClient client = new GroupChatClient();

        new Thread(() -> {
            System.out.println("线程启动");
            while (true) {
                try {
                    client.readMessageFromServer();
//                    Thread.sleep(1000);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();

        //发送数据给服务器
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            String next = scanner.nextLine();
            client.sendMessageToServer(next);
        }
    }
}
